<html>
<head>
    <title>Simple client</title>

    <script type="text/javascript">

        let ws;
        let image = '';
        function init() {
            // 获取服务端ip
            var ip_addr = document.location.hostname;
            window.WebSocket = window.WebSocket || window.MozWebSocket;
            ws = new WebSocket('ws://' + ip_addr + ':9001');         // 申请新的客户端

            // Connect to Web Socket
            //ws = new WebSocket("ws://localhost:9001/");

            // Set event handlers.
            ws.onopen = function () {
                output("onopen");
            };

            ws.onmessage = function (e) {
                // e.data contains received string.
                output("onmessage: " + e.data);
            };

            ws.onclose = function () {
                output("onclose");
            };

            ws.onerror = function (e) {
                output("onerror");
                console.log(e)
            };

        }

        function onSubmit() {
            var input = document.getElementById("input");
            // You can send message to the Web Socket using ws.send.
            // ws.send(input.value);
            // output("send: " + input.value);
            ws.send(image);
            output("send: " + image);
            input.value = "";
            input.focus();
        }

        function onCloseClick() {
            ws.close();
        }

        function output(str) {
            var log = document.getElementById("log");
            var escaped = str.replace(/&/, "&amp;").replace(/</, "&lt;").replace(/>/, "&gt;").replace(/"/, "&quot;"); // "
            log.innerHTML = escaped + "<br>" + log.innerHTML;
        }

    </script>
</head>
<body onload="init();">
<form onsubmit="onSubmit(); return false;" enctype="multipart/form-data">
    <input type="file" id="input" onchange="selectImage(this);">
    <input type="submit" value="Send">
    <button onclick="onCloseClick(); return false;">close</button>
</form>
<div id="log"></div>
<script>
    function selectImage(file) {
        if (!file.files || !file.files[0]) {
            return;
        }
        var reader = new FileReader();
        reader.onload = function (evt) {
            document.getElementById('input').src = evt.target.result;
            image = evt.target.result; //image 变量就是file文件二进制码
            console.log(image)
        }
        reader.readAsDataURL(file.files[0]);
    }
</script>
</body>
</html>